#include "qprojectloader.h"

#include "qupdatewidget.h"

#include "../../libs/running/qrunningmanager.h"

#include <QFile>
#include <QApplication>
#include <QSettings>
#include <QUuid>
#include <QProcess>

QProjectLoader::QProjectLoader():
    m_manager(new QRunningManager("Release"))
{
    init();
    m_updateWidget=new QUpdateWidget;
    m_updateWidget->setVisible(false);

    connect(m_manager,SIGNAL(load_signal(bool)),this,SLOT(loadFinish(bool)));
}

QProjectLoader::~QProjectLoader()
{
    if(m_manager!=NULL)
    {
        delete m_manager;
        m_manager=NULL;
    }
    if(m_updateWidget!=NULL)
    {
        delete m_updateWidget;
        m_updateWidget=NULL;
    }
}

void QProjectLoader::init()
{

    QSettings s(qApp->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    m_projectPath=s.value("project/path").toString();
    if(m_projectPath=="")
    {
        m_projectPath=qApp->applicationDirPath()+"/project";
    }
    m_uuid=s.value("project/uuid").toString();
    if(m_uuid=="")
    {
        m_uuid=QUuid::createUuid().toString();
        s.setValue("project/uuid",m_uuid);
    }
}

void QProjectLoader::run()
{
    if(m_manager!=NULL)
    {
        m_manager->load(m_projectPath);
    }
    else
    {
        m_updateWidget->setVisible(true);
    }
}

void QProjectLoader::loadFinish(bool success)
{
    if(success)
    {
        m_manager->start();
    }
    else
    {
        m_updateWidget->setVisible(true);
    }
}

void QProjectLoader::updateFinish()
{
    QProcess::startDetached(QApplication::applicationDirPath()+"/softUpdate.exe");
    if(m_manager!=NULL)
    {
        delete m_manager;
        m_manager=NULL;
    }
    if(m_updateWidget!=NULL)
    {
        delete m_updateWidget;
        m_updateWidget=NULL;
    }
}
